<template>
    <div class="container">
        <div class="header">
            <!-- 优化选择器布局 -->
            <div class="filters">
                <el-select
                    v-model="selectedSemester"
                    placeholder="请选择学期"
                    @change="filterStudents"
                    style="width: 200px; margin-right: 10px;"
                    clearable
                >
                    <el-option label="全部学期" :value="''" />
                    <el-option
                        v-for="item in semesterList"
                        :key="item"
                        :label="item"
                        :value="item"
                    />
                </el-select>
                <el-select
                    v-model="selectedClass"
                    placeholder="请选择班级"
                    @change="filterStudents"
                    style="width: 200px; margin-right: 10px;"
                    clearable
                >
                    <el-option label="全部班级" :value="0" />
                    <el-option
                        v-for="item in classList"
                        :key="item.clazzId"
                        :label="item.clazzName"
                        :value="item.clazzId"
                    />
                </el-select>
            </div>
            <el-button type="primary" @click="openEditDialog({})" icon="Plus">添加学生</el-button>
        </div>

        <!-- 优化表格 -->
        <el-table
            :data="paginatedStudentList"
            border
            stripe
            highlight-current-row
            style="width: 100%; margin-bottom: 20px; font-size: 11px;"
            v-loading="loading"
            max-height="calc(100vh - 200px)"
            empty-text="暂无数据"
        >
            <el-table-column prop="studentId" label="学生ID" width="70" sortable />
            <el-table-column prop="studentNumber" label="学号" width="90" sortable />
            <el-table-column prop="name" label="姓名" width="90" sortable />
            <el-table-column prop="gender" label="性别" width="60" sortable>
                <template #default="scope">
                    <el-tag :type="scope.row.gender === '男' ? 'primary' : 'success'" size="small">
                        {{ scope.row.gender }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="院系" width="90" sortable>
                <template #default="scope">
                    <el-tag size="small">{{ getDepartmentName(scope.row.departmentCode) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="birthday" label="生日" width="90" sortable>
                <template #default="scope">
                    {{ formatDate(scope.row.birthday) }}
                </template>
            </el-table-column>
            <el-table-column prop="recordTime" label="记录时间" width="100" sortable />
            <el-table-column prop="origin" label="籍贯" width="90" />
            <el-table-column label="班级" width="90" sortable>
                <template #default="scope">
                    <el-tag size="small">{{ getClazzName(scope.row.clazzId) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="140" fixed="right">
                <template #default="scope">
                    <el-button-group>
                        <el-button size="small" @click="openEditDialog(scope.row)" icon="Edit" type="primary">编辑</el-button>
                        <el-button size="small" @click="deleteStudent(scope.row.studentId)" icon="Delete" type="danger">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 优化分页 -->
        <div class="pagination-wrapper">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="filteredStudentList.length"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="pageSize"
                :current-page="currentPage"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            />
        </div>

        <!-- 添加/编辑对话框 -->
        <el-dialog :title="currentStudent.studentId ? '编辑学生' : '添加学生'" v-model="dialogVisible" width="500px">
            <el-form :model="currentStudent" :rules="rules" ref="formRef" label-width="80px">
                <el-form-item label="学号" prop="studentNumber">
                    <el-input v-model="currentStudent.studentNumber" placeholder="请输入学号" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="currentStudent.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="currentStudent.gender" placeholder="请选择性别" style="width: 100%">
                        <el-option label="男" value="m" />
                        <el-option label="女" value="f" />
                    </el-select>
                </el-form-item>
                <el-form-item label="班级" prop="clazzId">
                    <el-select v-model="currentStudent.clazzId" placeholder="请选择班级">
                        <el-option
                            v-for="item in classList"
                            :key="item.clazzId"
                            :label="item.clazzName"
                            :value="item.clazzId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="生日">
                    <el-date-picker
                        v-model="currentStudent.birthday"
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                    />
                </el-form-item>
                <el-form-item label="籍贯">
                    <el-input v-model="currentStudent.origin" placeholder="请输入籍贯" />
                </el-form-item>
                <el-form-item label="院系">
                    <el-select v-model="currentStudent.departmentCode" placeholder="请选择院系">
                        <el-option
                            v-for="department in departmentList"
                            :key="department.code"
                            :label="department.name"
                            :value="department.code"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="记录时间">
                    <el-input v-model="currentStudent.recordTime" placeholder="请输入记录时间" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="currentStudent.studentId ? updateStudent() : addStudent()">
                        {{ currentStudent.studentId ? '更新' : '添加' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api/request.js'
import { getAllClasses, getAllStudents, getAllSemesters, getStudentsSortedByTotalScore } from '../api/request.js'
import axios from 'axios'

const studentList = ref([])
const classList = ref([])
const semesterList = ref(['2023春季学期', '2023秋季学期']) // 学期列表
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加学生')
const formRef = ref(null)
const selectedClass = ref(0)
const selectedSemester = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const departmentList = ref([])

const currentStudent = ref({
    studentId: null,
    studentNumber: null,
    password: '',
    name: '',
    gender: '',
    birthday: '',
    origin: '',
    departmentCode: null,
    clazzId: null,
    recordTime: ''
})

const rules = {
    studentNumber: [{ required: true, message: '请输入学号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    clazzId: [{ required: true, message: '请选择班级', trigger: 'change' }],
    departmentCode: [{ required: true, message: '请输入院系代码', trigger: 'blur' }]
}

// 优化getClassName方法
const getClassName = (classId) => {
    if (!classId) {
        console.warn('classId为空:', classId);
        return '未分配班级';  // 修改默认值为"未分配班级"
    }
    const clazzItem = classList.value.find(item => item.clazzId === Number(classId));
    if (!clazzItem) {
        console.warn('未找到匹配的班级:', classId, '班级列表:', classList.value);
    }
    return clazzItem ? clazzItem.clazzName : '未知班级';
}

// 计算属性：根据选中的班级和学期过滤学生列表
const filteredStudentList = computed(() => {
    let list = studentList.value || []
    console.log('原始学生列表:', list) // 调试日志
    if (selectedClass.value) {
        list = list.filter(student => student.clazzId === selectedClass.value)
    }
    if (selectedSemester.value) {
        list = list.filter(student => student.recordTime === selectedSemester.value)
    }
    console.log('过滤后的学生列表:', list) // 调试日志
    return list
})

// 计算属性：分页后的学生列表
const paginatedStudentList = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return studentList.value.slice(start, end)
})

// 获取院系数据
onMounted(async () => {
    loading.value = true;
    try {
        // 先加载院系数据
        const res = await api.department.getAll();
        departmentList.value = res.data || [];
        console.log('院系数据:', departmentList.value);

        // 再加载学生数据
        const studentsRes = await getAllStudents();
        studentList.value = studentsRes.data || [];
        console.log('学生数据:', studentList.value);

    } catch (error) {
        console.error('加载错误:', error);
        ElMessage.error('加载数据失败');
    } finally {
        loading.value = false;
    }
});

// 优化getDepartmentName方法
const getDepartmentName = (code) => {
    if (!code) {
        console.warn('院系代码为空:', code);
        return '未分配院系';
    }
    // 转换为数字类型进行比较
    const searchCode = Number(code);
    console.log('正在查找院系代码:', searchCode, '类型:', typeof searchCode);

    const department = departmentList.value.find(item => {
        console.log('遍历院系:', item.code, '类型:', typeof item.code);
        return item.code === searchCode;
    });

    if (!department) {
        console.warn('未找到匹配的院系:', code, '院系列表:', departmentList.value);
    }
    return department ? department.name : '未知院系';
};

// 优化班级数据获取逻辑
onMounted(async () => {
    loading.value = true;
    try {
        // 先加载班级数据，确保classList先于studentList加载
        const classesRes = await api.class.getAll();
        const rawClassList = classesRes?.data || [];
        classList.value = Array.isArray(rawClassList) 
            ? rawClassList.map(c => ({
                clazzId: Number(c.clazzId) || 0,  // 使用clazzId
                clazzName: c.clazzName || '未命名班级'  // 使用clazzName
            }))
            : [];
        console.log('班级数据加载完成:', classList.value);

        // 再加载学生数据
        const studentsRes = await getAllStudents();
        const rawStudentList = Array.isArray(studentsRes) ? studentsRes : [];
        studentList.value = rawStudentList;
        console.log('学生数据加载完成:', studentList.value);

        // 检查学生数据中的class_id字段
        studentList.value.forEach(student => {
            if (!student.class_id) {
                console.warn('学生未分配班级:', student);
            }
        });

    } catch (error) {
        console.error('加载数据出错:', error);
        ElMessage.error('加载数据失败');
    } finally {
        loading.value = false;
    }
});

// 添加学生
const openEditDialog = (student) => {
    currentStudent.value = { ...student };
    dialogVisible.value = true;
}

// 删除学生
const deleteStudent = async (id) => {
    ElMessageBox.confirm('确定要删除该学生吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await api.student.delete(id)
            if (res.code === 1) {
                ElMessage.success('删除成功')
                fetchStudents()
            } else {
                ElMessage.error(res.msg || '删除失败')
            }
        } catch (error) {
            console.error('删除学生出错:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return

    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const postData = {
                    studentId: currentStudent.value.studentId,
                    studentNumber: Number(currentStudent.value.studentNumber),
                    name: currentStudent.value.name,
                    gender: currentStudent.value.gender === '男' ? 'm' : 'f',
                    clazzId: Number(currentStudent.value.clazzId),
                    password: currentStudent.value.password,
                    recordTime: currentStudent.value.recordTime,
                    birthday: currentStudent.value.birthday,
                    origin: currentStudent.value.origin,
                    departmentCode: Number(currentStudent.value.departmentCode)
                }
                
                let res
                if (currentStudent.value.studentId) {
                    res = await api.student.update(postData)
                } else {
                    res = await api.student.add(postData)
                }

                if (res.code === 1) {
                    ElMessage.success(currentStudent.value.studentId ? '更新成功' : '添加成功')
                    dialogVisible.value = false
                    fetchStudents()
                } else {
                    ElMessage.error(res.msg || (currentStudent.value.studentId ? '更新失败' : '添加失败'))
                }
            } catch (error) {
                console.error(currentStudent.value.studentId ? '更新学生出错:' : '添加学生失败:', error)
                ElMessage.error(currentStudent.value.studentId ? '更新失败' : '添加失败')
            }
        }
    })
}

// 根据选中的班级和学期过滤学生列表
const filterStudents = () => {
    let list = studentList.value || []
    if (selectedClass.value !== 0) {
        list = list.filter(student => student.clazzId === selectedClass.value)
    }
    if (selectedSemester.value !== '') {
        list = list.filter(student => student.recordTime === selectedSemester.value)
    }
    return list
}

const formatDate = (date) => {
    if (!date) return ''
    return new Date(date).toLocaleDateString('zh-CN')
}

const fetchStudents = async () => {
    loading.value = true
    try {
        const res = await getAllStudents()
        console.log('API响应数据:', res)
        if (res.code === 1) {
            studentList.value = res.data || []
            console.log('学生列表:', studentList.value)
        } else {
            ElMessage.error(res.msg || '获取学生列表失败')
        }
    } catch (error) {
        console.error('获取学生列表出错:', error)
        ElMessage.error('获取学生列表失败')
    } finally {
        loading.value = false
    }
}

const fetchClasses = async () => {
    try {
        const res = await getAllClasses()
        console.log('API响应数据:', res)
        if (res.code === 1) {
            classList.value = res.data || []
            console.log('班级列表:', classList.value)
        } else {
            ElMessage.error(res.msg || '获取班级列表失败')
        }
    } catch (error) {
        console.error('获取班级列表出错:', error)
        ElMessage.error('获取班级列表失败')
    }
}

const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1 // 重置当前页码
}

const handlePageChange = (newPage) => {
    currentPage.value = newPage
}

// 添加学生
const addStudent = async () => {
    try {
        await axios.post('/students', currentStudent.value);
        ElMessage.success('学生添加成功');
        fetchStudents();
        dialogVisible.value = false;
    } catch (error) {
        console.error('添加学生成功:');
        ElMessage.error('添加学生成功');
    }
};

// 更新学生
const updateStudent = async () => {
    try {
        await axios.put('/students', currentStudent.value);
        ElMessage.success('学生信息更新成功');
        fetchStudents();
        dialogVisible.value = false;
    } catch (error) {
        console.error('更新学生失败:', error);
        ElMessage.error('更新学生失败');
    }
};

// 获取班级名称
const getClazzName = (clazzId) => {
    const clazz = classList.value.find(clazz => clazz.clazzId === clazzId);
    return clazz ? clazz.clazzName : '未知班级';
};

// 确保日期格式正确
currentStudent.value.birthday = "2023-04-04"; // 示例日期
</script>

<style scoped>
.container {
    padding: 20px;
    height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.filters {
    display: flex;
    align-items: center;
}

.pagination-wrapper {
    margin-top: 20px;
    padding: 10px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    display: flex;
    justify-content: flex-end;
}

.el-table {
    flex: 1;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
</style>